<?
//本文档存放网站常用的函数，直接供一次过记录多个函数，让系统使用


function print_r2($array)
{
    echo "<pre>";
    print_r($array);
    echo "</pre>";
}

//================================
// 获取当前路径包含前缀及路径及参数
//================================



function curPageURL() 
{
  $pageURL = 'http';

  if ($_SERVER["HTTPS"] == "on") 
  {
    $pageURL .= "s";
  }
  $pageURL .= "://";

  if ($_SERVER["SERVER_PORT"] != "80") 
  {
    $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
  } 
  else 
  {
    $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
  }
  return $pageURL;
}


function check_user_account($user_mid){
	
	$userinfo = select_one_line_all_items($table_Prefix."user","mid = '".$user_mid."'");
	
	
	$config_info = select_one_line_all_items("config","id = '1'");
	
	if($userinfo['balance'] < $config_info['user_account']){
		send_msg();
	}
	
}

function send_msg(){

}

function cat_list($cat_id = 0, $selected = 0, $re_type = true, $level = 0, $res = '')
{
  
    global $table_Prefix;
	
	static $res = NULL;
    if ($res === NULL)
    {
       $data = read_static_cache('cat_pid_releate');
	   
       if ($data === false)
       {
          $sql = "SELECT c.* , COUNT(s.nid) AS has_children ".
                'FROM ' . $table_Prefix.'department' . " AS c ".
                "LEFT JOIN " . $table_Prefix.'department' . " AS s ON s.parent_id=c.nid ".
                "GROUP BY c.nid ".
                'ORDER BY c.parent_id, c.nid ASC';
        
		  
		  $result_term0 = mysql_query($sql);
		
          while($row = mysql_fetch_array($result_term0))
          {
              $res[]=$row;
			
          }
		  
		
		  //如果数组过大，不采用静态缓存方式
          if (count($res) <= 1000)
          {
              write_static_cache('cat_pid_releate', $res); 
			  
          }
        }
        else
        {
            $res = $data;
        }
		
    }

    if (empty($res) == true)
    {
        return $re_type ? '' : array();
    }

    $options = cat_options($cat_id, $res); // 获得指定分类下的子分类的数组
 
    $children_level = 99999; //大于这个分类的将被删除
    
        foreach ($options as $key => $val)
        {
            if ($val['level'] > $children_level)
            {
                unset($options[$key]);
            }
            else
            {
                if ($val['status'] == '关闭')
                {
                    unset($options[$key]);
                    if ($children_level > $val['level'])
                    {
                        $children_level = $val['level']; //标记一下，这样子分类也能删除
                    }
                }
                else
                {
                    $children_level = 99999; //恢复初始值
                }
            }
        }
    

    /* 截取到指定的缩减级别 */
    if ($level > 0)
    {
        if ($cat_id == 0)
        {
            $end_level = $level;
        }
        else
        {
            $first_item = reset($options); // 获取第一个元素
            $end_level  = $first_item['level'] + $level;
        }

        /* 保留level小于end_level的部分 */
        foreach ($options AS $key => $val)
        {
            if ($val['level'] >= $end_level)
            {
                unset($options[$key]);
            }
        }
    }

    if ($re_type == true)
    {
        $select = '';
        foreach ($options AS $var)
        {
            $select .= '<option value="' . $var['nid'] . '" ';
            $select .= ($selected == $var['nid']) ? "selected='ture'" : '';
            $select .= '>';
            if ($var['level'] > 0)
            {
                $select .= str_repeat('&nbsp;', $var['level'] * 4);
            }
            $select .= htmlspecialchars(addslashes($var['name']), ENT_QUOTES) . '</option>';
        }

        return $select;
    }
    else
    {
        foreach ($options AS $key => $value)
        {
           // $options[$key]['url'] = build_uri('category', array('cid' => $value['cat_id']), $value['cat_name']);
        }

        return $options;
    }
}





/**
 * 过滤和排序所有分类，返回一个带有缩进级别的数组
 *
 * @access  private
 * @param   int     $cat_id     上级分类ID
 * @param   array   $arr        含有所有分类的数组
 * @param   int     $level      级别
 * @return  void
 */
function cat_options($spec_cat_id, $arr)
{
    static $cat_options = array();
	
	
    if (isset($cat_options[$spec_cat_id]))
    {
        return $cat_options[$spec_cat_id];
    }
	
    if (!isset($cat_options[0]))
    {
		
        $level = $last_cat_id = 0;
        $options = $cat_id_array = $level_array = array();
        $data = false;
        if ($data === false)
        {
            while (!empty($arr))
            {
                foreach ($arr AS $key => $value)
                {
                    $cat_id = $value['nid'];
                    if ($level == 0 && $last_cat_id == 0)
                    {
						
                        if ($value['parent_id'] > 0)
                        {
                            break;
                        }

                        $options[$cat_id]          = $value;
                        $options[$cat_id]['level'] = $level;
                        $options[$cat_id]['id']    = $cat_id;
                        $options[$cat_id]['name']  = $value['name'];
						
                        unset($arr[$key]);

                        if ($value['has_children'] == 0)
                        {
                            continue;
                        }
                        $last_cat_id  = $cat_id;
                        $cat_id_array = array($cat_id);
                        $level_array[$last_cat_id] = ++$level;
                        continue;
                    }

                    if ($value['parent_id'] == $last_cat_id)
                    {
						
                        $options[$cat_id]          = $value;
                        $options[$cat_id]['level'] = $level;
                        $options[$cat_id]['id']    = $cat_id;
                        $options[$cat_id]['name']  = $value['name'];
                        unset($arr[$key]);

                        if ($value['has_children'] > 0)
                        {
                            if (end($cat_id_array) != $last_cat_id)
                            {
                                $cat_id_array[] = $last_cat_id;
                            }
                            $last_cat_id    = $cat_id;
                            $cat_id_array[] = $cat_id;
                            $level_array[$last_cat_id] = ++$level;
                        }
                    }
                    elseif ($value['parent_id'] > $last_cat_id)
                    {
                        break;
                    }
                }

                $count = count($cat_id_array);
                if ($count > 1)
                {
                    $last_cat_id = array_pop($cat_id_array);
                }
                elseif ($count == 1)
                {
                    if ($last_cat_id != end($cat_id_array))
                    {
                        $last_cat_id = end($cat_id_array);
                    }
                    else
                    {
                        $level = 0;
                        $last_cat_id = 0;
                        $cat_id_array = array();
                        continue;
                    }
                }

                if ($last_cat_id && isset($level_array[$last_cat_id]))
                {
                    $level = $level_array[$last_cat_id];
                }
                else
                {
                    $level = 0;
                }
            }
           
        }
        else
        {
            $options = $data;
        }
        $cat_options[0] = $options;
    }
    else
    {
        $options = $cat_options[0];
    }
	
    if (!$spec_cat_id)
    {
        return $options;
    }
    else
    {
		
        if (empty($options[$spec_cat_id]))
        {
            return array();
        }

        $spec_cat_id_level = $options[$spec_cat_id]['level'];
		
        foreach ($options AS $key => $value)
        {
			
            if ($key != $spec_cat_id)
            {
				
                unset($options[$key]);
            }
            else
            {
                break;
            }
        }

        $spec_cat_id_array = array();
        foreach ($options AS $key => $value)
        {
            if (($spec_cat_id_level == $value['level'] && $value['nid'] != $spec_cat_id) ||
                ($spec_cat_id_level > $value['level']))
            {
                break;
            }
            else
            {
                $spec_cat_id_array[$key] = $value;
            }
        }
        $cat_options[$spec_cat_id] = $spec_cat_id_array;
		
        return $spec_cat_id_array;
    }
}


function get_department_list(){
	 
	 global $table_Prefix;
 	$sql = "SELECT c.* , COUNT(s.nid) AS has_children ".
                'FROM ' . $table_Prefix.'department' . " AS c ".
                "LEFT JOIN " . $table_Prefix.'department' . " AS s ON s.parent_id=c.nid ".
                "GROUP BY c.nid ".
                'ORDER BY c.parent_id, c.nid ASC';
        
	$result_term0 = mysql_query($sql);

    while($row = mysql_fetch_array($result_term0))
    {
       $res[]=$row;	
    }
	return $res;
}

function get_department_top_id($id){
	
	global $table_Prefix;
    
	$father_id = '';
	
	$department_info = select_one_line_all_items($table_Prefix."department","nid=".$id); 
	
	$father_id = $department_info['nid'];
	if($department_info['parent_id'] > 0){
		
		return get_department_top_id($department_info['parent_id']); 
		
	}
    
	return $father_id;
	
}

/**
 * 获得指定分类下所有底层分类的ID
 *
 * @access  public
 * @param   integer     $cat        指定的分类ID
 * @return  string
 */
function get_children($cat = 0,$res = '')
{
    return  db_create_in(array_unique(array_merge(array($cat), array_keys(cat_list($cat, 0, false,0,$res)))));
}

/**
 * 创建像这样的查询: "IN('a','b')";
 *
 * @access   public
 * @param    mix      $item_list      列表数组或字符串
 * @param    string   $field_name     字段名称
 *
 * @return   void
 */
 
function db_create_in($item_list, $field_name = '')
{
    if (empty($item_list))
    {
        return $field_name . " IN ('') ";
    }
    else
    {
        if (!is_array($item_list))
        {
            $item_list = explode(',', $item_list);
        }
        $item_list = array_unique($item_list);
        $item_list_tmp = '';
        foreach ($item_list AS $item)
        {
            if ($item !== '')
            {
                $item_list_tmp .= $item_list_tmp ? ",'$item'" : "'$item'";
            }
        }
        if (empty($item_list_tmp))
        {
            return $field_name . " IN ('') ";
        }
        else
        {
            return $field_name . ' IN (' . $item_list_tmp . ') ';
        }
    }
}


function admin_priv($priv_str)
{
   
    if ($_SESSION['quanxian'] == 'all')
    {
        return true;
    }
	
	$quanxian_list = explode(',',$_SESSION['quanxian']);
	

    if (!in_array($priv_str,$quanxian_list))
    {
       
        echo '<script>alert("对不起,您没有执行此项操作的权限!");window.location.href="../index.php?nav-itemed=index";</script>';
        
        return false;
    }
    else
    {
        return true;
    }
}



/**
 * 读结果缓存文件
 *
 * @params  string  $cache_name
 *
 * @return  array   $data
 */
function read_static_cache($cache_name)
{
    if ((DEBUG_MODE & 2) == 2)
    {
        return false;
    }
    static $result = array();
    if (!empty($result[$cache_name]))
    {
        return $result[$cache_name];
    }
    $cache_file_path = ROOT_PATH . '/temp/static_caches/' . $cache_name . '.php';
    if (file_exists($cache_file_path))
    {
        include_once($cache_file_path);
        $result[$cache_name] = $data;
        return $result[$cache_name];
    }
    else
    {
        return false;
    }
}

/**
 * 写结果缓存文件
 *
 * @params  string  $cache_name
 * @params  string  $caches
 *
 * @return
 */
function write_static_cache($cache_name, $caches)
{
    if ((DEBUG_MODE & 2) == 2)
    {
        return false;
    }
	
    $cache_file_path = ROOT_PATH . '/temp/static_caches/' . $cache_name . '.php';
    $content = "<?php\r\n";
    $content .= "\$data = " . var_export($caches, true) . ";\r\n";
    $content .= "?>";
    file_put_contents($cache_file_path, $content, LOCK_EX);
	
}


function clear_cache(){
	
	unlink(ROOT_PATH . '/temp/static_caches/cat_pid_releate.php');
	
}

?>